package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.feign.VMService;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 自动补货任务生成job
 */
@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService vmService;

    /**
     * 售货机扫描任务
     *
     * @param param
     * @return
     */
    @XxlJob("supplyJobHander")
    public ReturnT<String> supplyJobHander(String param) {
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        //获取分片总数
        int total = shardingVo.getTotal();
        //分片索引
        int index = shardingVo.getIndex();


        QueryWrapper<VendingMachineEntity> qw = new QueryWrapper<>();
        //查询所有运营的售货机
        qw.lambda().eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING).apply("mod(id," + total + " ) = " + index);

        List<VendingMachineEntity> list = vmService.list(qw);
        for (VendingMachineEntity vendingMachineEntity : list) {
            XxlJobLogger.log("扫描售货机" + vendingMachineEntity.getInnerCode());
            vmService.sendSupplyTask(vendingMachineEntity.getInnerCode());
        }
        return ReturnT.SUCCESS;
    }
}
